import Taro from '@tarojs/taro'
import { post } from '@/utils/request';
import { showLocationGuide } from '@/composables/locationGuide';

// export const appid = 'wxd2a505183cc8e9d3';

// 配置参数
const APPID = 'wxd2a505183cc8e9d3';
const REDIRECT_URI = `${window.location.origin}`; // 需与公众号配置的域名一致
// const SCOPE = 'snsapi_base'; // 或 snsapi_userinfo
const SCOPE = 'snsapi_userinfo';
const STATE = '123'; // 可选，用于防CSRF
const DEBUG_LOG_STORAGE_KEY = 'authDebugLogs';
const DEBUG_ENABLE_STORAGE_KEY = 'authDebugEnabled';

/**
 * 微信授权管理类
 * 根据环境判断授权调用时机
 */
export class WechatAuth {
  private static instance: WechatAuth;
  
  private constructor() {}
  
  static getInstance(): WechatAuth {
    if (!WechatAuth.instance) {
      WechatAuth.instance = new WechatAuth();
    }
    return WechatAuth.instance;
  }

  private formatDebugArg(arg: unknown) {
    if (typeof arg === 'string') return arg;
    try {
      return JSON.stringify(arg);
    } catch (error) {
      return String(arg);
    }
  }

  private appendDebugLog(message: string) {
    try {
      const cache: Array<{ timestamp: number; message: string }> =
        Taro.getStorageSync(DEBUG_LOG_STORAGE_KEY) || [];
      const nextCache = [...cache, { timestamp: Date.now(), message }];
      if (nextCache.length > 30) {
        nextCache.splice(0, nextCache.length - 30);
      }
      Taro.setStorageSync(DEBUG_LOG_STORAGE_KEY, nextCache);
    } catch (error) {
      console.error('写入调试日志失败:', error);
    }
  }

  private isDebugEnabled() {
    return !!Taro.getStorageSync(DEBUG_ENABLE_STORAGE_KEY);
  }

  private updateDebugFlag(urlParams: URLSearchParams) {
    const debugParam = urlParams.get('debug');
    if (debugParam === '1') {
      Taro.setStorageSync(DEBUG_ENABLE_STORAGE_KEY, true);
      console.log('[wechat-auth] Debug 模式通过 URL 启用并已缓存');
    } else if (debugParam === '0') {
      Taro.removeStorageSync(DEBUG_ENABLE_STORAGE_KEY);
      console.log('[wechat-auth] Debug 模式通过 URL 关闭并已清理缓存');
    }
  }

  private debugLog(...args: unknown[]) {
    if (!this.isDebugEnabled()) return;
    const message = args.map((item) => this.formatDebugArg(item)).join(' ');
    this.appendDebugLog(message);
    console.log('[wechat-auth]', ...args);
  }

  /**
   * 判断是否为开发环境
   */
  private isDevelopment(): boolean {
    return process.env.NODE_ENV === 'development' || 
           Taro.getSystemInfoSync().platform === 'devtools';
  }

  /**
   * 判断是否为生产环境
   */
  private isProduction(): boolean {
    return process.env.NODE_ENV === 'production' && 
           Taro.getSystemInfoSync().platform !== 'devtools';
  }

  /**
   * 判断是否在微信环境中
   */
  private isWechatEnvironment(): boolean {
    const systemInfo = Taro.getSystemInfoSync();
    return systemInfo.platform === 'wechat' || 
           systemInfo.platform === 'weapp' ||
           (typeof window !== 'undefined' && /MicroMessenger/i.test(navigator.userAgent));
  }

  /**
   * 检查是否需要授权
   * 授权调用时机：
   * 1. 生产环境 + 微信环境 + 无token
   * 2. 生产环境 + 微信环境 + token过期
   */
  shouldAuth(): boolean {
    // 开发环境不需要授权
    if (this.isDevelopment()) {
      console.log('开发环境，跳过微信授权');
      return false;
    }

    // 非微信环境不需要授权
    if (!this.isWechatEnvironment()) {
      console.log('非微信环境，跳过微信授权');
      return false;
    }

    // 检查token
    // const token = Taro.getStorageSync('token');
    // if (!token) {
    //   console.log('无token，需要微信授权');
    //   return true;
    // }
    return true;

    // 检查token是否过期（这里可以根据实际需求调整）
    // const tokenExpireTime = Taro.getStorageSync('tokenExpireTime');
    // if (tokenExpireTime && Date.now() > tokenExpireTime) {
    //   console.log('token已过期，需要重新授权');
    //   Taro.removeStorageSync('token');
    //   Taro.removeStorageSync('tokenExpireTime');
    //   return true;
    // }

    // console.log('已有有效token，无需授权');
    // return false;
  }

  /**
   * 执行微信授权
   */
  async authorize(): Promise<void> {
    if (!this.shouldAuth()) {
      return;
    }

    try {
      console.log('开始微信授权流程');
      
      // 生成授权URL
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=${SCOPE}&state=${STATE}#wechat_redirect`;
      
      // 跳转到微信授权页
      if (typeof window !== 'undefined') {
        // localStorage.setItem('authUrl', authUrl)
        const urlParams = new URLSearchParams(window.location.search);
        const recommend = urlParams.get('recommend');
        if(recommend) {
          localStorage.setItem('recommend', recommend)
        }
        setTimeout(() => {
          window.location.href = authUrl;
        }, 60);
        
      } else {
        // 小程序环境使用Taro的跳转
        Taro.navigateTo({
          url: authUrl
        });
      }
    } catch (error) {
      console.error('微信授权失败:', error);
      Taro.showToast({
        title: '授权失败，请重试',
        icon: 'none'
      });
    }
  }

  /**
   * 处理授权回调
   * 在授权回调页面调用此方法
   */
  handleAuthCallback(): void {
    try {
      // 获取URL参数
      const urlParams = new URLSearchParams(window.location.search);
      this.updateDebugFlag(urlParams);
      const code = urlParams.get('code');
      const state = urlParams.get('state');

      // 获取推荐码参数并保存到缓存
      this.handleReferralCode();

      this.debugLog('handleAuthCallback 参数:', { code, state });

      if (code && state === STATE) {
        this.debugLog('授权成功，获取到code:', code);
        
        // 这里应该调用后端接口，用code换取access_token
        this.exchangeCodeForToken(code);
      } else {
        console.error('授权失败，缺少必要参数');
        this.debugLog('授权失败，缺少必要参数');
        Taro.showToast({
          title: '授权失败',
          icon: 'none'
        });
        showLocationGuide();
      }
    } catch (error) {
      console.error('处理授权回调失败:', error);
      this.debugLog('处理授权回调失败详情:', error);
    }
  }

  /**
   * 处理推荐码参数
   * 从URL获取推荐码并保存到缓存
   */
  handleReferralCode(): void {
    try {
      // 获取URL参数
      const urlParams = new URLSearchParams(window.location.search);
      const referralCode = urlParams.get('ref') || urlParams.get('referral') || urlParams.get('code');
      
      if (referralCode) {
        // 保存推荐码到缓存
        Taro.setStorageSync('referralCode', referralCode);
        console.log('推荐码已保存到缓存:', referralCode);
        
        // 可选：显示提示信息
        Taro.showToast({
          title: '推荐码已记录',
          icon: 'success',
          duration: 1500
        });
      }
    } catch (error) {
      console.error('处理推荐码失败:', error);
    }
  }

  /**
   * 获取缓存的推荐码
   */
  getReferralCode(): string | null {
    try {
      return Taro.getStorageSync('referralCode');
    } catch (error) {
      console.error('获取推荐码失败:', error);
      return null;
    }
  }

  /**
   * 清除推荐码缓存
   */
  clearReferralCode(): void {
    try {
      Taro.removeStorageSync('referralCode');
      console.log('推荐码缓存已清除');
    } catch (error) {
      console.error('清除推荐码缓存失败:', error);
    }
  }

  /**
   * 用code换取access_token
   */
  private async exchangeCodeForToken(code: string): Promise<void> {
    try {
      // 导入post函数
      
      
      // 调用后端接口
      const response = await post('/my/updateOpenID', { code });
      
      console.log('后端接口响应:', response);
      Taro.redirectTo({
        url: '/pages/home/home'
      });

      // if (response.code === 0) {
      //   // 保存token和过期时间
      //   const token = response.data.token || 'wechat_token_' + Date.now();
      //   const expireTime = response.data.expireTime || Date.now() + 7200 * 1000;
        
      //   Taro.setStorageSync('token', token);
      //   Taro.setStorageSync('tokenExpireTime', expireTime);
        
      //   console.log('授权成功，token已保存');
        
      //   // 跳转到首页或指定页面
      //   Taro.redirectTo({
      //     url: '/pages/home/home'
      //   });
      // } else {
      //   throw new Error(response.message || '授权失败');
      // }
    } catch (error) {
      console.error('换取token失败:', error);
      Taro.showToast({
        title: '授权失败',
        icon: 'none'
      });
    }
  }

  /**
   * 检查授权状态
   */
  checkAuthStatus(): boolean {
    const token = Taro.getStorageSync('token');
    const tokenExpireTime = Taro.getStorageSync('tokenExpireTime');
    
    return !!(token && tokenExpireTime && Date.now() < tokenExpireTime);
  }
}

// 导出单例实例
export const wechatAuth = WechatAuth.getInstance();

// 兼容旧代码的导出
export const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=${SCOPE}&state=${STATE}#wechat_redirect`;